<template>
  <div class="weightItem">
    <van-nav-bar :title="$route.meta.title" left-arrow :border="false" @click-left="onClickLeft" class="nav-bar">
      <template #right>
        <!-- <van-icon name="search" size="24" /> -->
      </template>
    </van-nav-bar>
    <div class="item-style">
      <van-row gutter="20" type="flex" justify="left" align="center">
        <van-col span="12">
          <van-field v-model="deviceName" name="deviceName" label="称量仪器" readonly placeholder="请选择称量仪器" input-align="center">
            <template #input>
              <device-name :deviceName="deviceName" @change="getDeviceCode"></device-name>
            </template>
          </van-field>
        </van-col>
        <van-col span="12">
          <van-field v-model="instCode" name="instCode" label="仪器编号" readonly input-align="center"></van-field>
        </van-col>
      </van-row>

      <van-row gutter="20" type="flex" justify="left" align="center">
        <!-- <van-col span="12">
          <van-field v-model="materialType" name="materialType" label="物料类型" input-align="center" left-icon="scan" @click-left-icon="openScan('material')" class="deviceStyle">
            <template #input>
              <material-type :materialTypeName="materialTypeName" v-model="materialType" />
            </template>
          </van-field>
        </van-col> -->
        <van-col span="12">
          <van-field v-model="materialName" name="materialName" label="物料名称" input-align="center" readonly clickable placeholder="请选择" @click="showMaterialNamePicker = true">
            <template #input>
              <!-- <material-name :materialName="materialName" :materialType="materialType" v-model="materialCode" @change="changeMater" /> -->
            </template>
          </van-field>
        </van-col>
        <van-col span="12" style="padding-right: 10px">
          <van-field v-model="batch" name="batch" label="称重批次" clickable input-align="center">
            <template #input>
              <batch-list :batchIdArr="batchIdArr" :batchId="batchId" @chooseValue="updataBatch"></batch-list>
            </template>
          </van-field>
        </van-col>
        <!-- <van-col span="12">
          <van-field label="检验记录" input-align="center" readonly clickable v-model="recordName" placeholder="请选择" @click="showPicker = true"></van-field>
        </van-col> -->
        <!-- <van-col span="12" style="padding-right: 10px">
          <van-field v-model="deviceItemCode" name="deviceItemCode" label="称重项目:" readonly placeholder="请选择称重项目">
            <template #input>
              <mult-select :dataList="deviceItemArr" @chooseValue="updataDeviceItemCode" />
            </template>
          </van-field>
        </van-col> -->
      </van-row>
      <div style="display: flex; justify-content: space-between">
        <van-tag plain type="primary" style="margin: 20px 10px 10px 10px">检验列表</van-tag>
        <van-loading v-if="connectState" type="spinner" style="float: right; margin-right: 20px; margin-top: 15px" color="#1989fa" size="30px" />
      </div>

      <div class="checkItem">
        <van-list :finished="finished" finished-text="暂无数据">
          <van-swipe-cell v-for="(v, i) in itemList" :key="i" ref="swipecell">
            <van-cell title-class="custom-title" value-class="custom-value" label-class="custom-label">
              <template #title>
                <div class="titleStyle">
                  <span class="custom-title">{{ v.materialName }}</span>
                  <div class="controlBtn">
                    <!-- <van-button
                      icon="scan"
                      style="padding: 0px 10px"
                      ref="sampleConfirm"
                      @click="openScan('sample', v, i)"
                      >样品确认</van-button
                    > -->
                    <button ref="startWeight" :disabled="ishandle" @click="getWeightNum(v, i)">开始</button>

                    <button v-if="v.weighMode != '1' && v.weighMode != '25'" @click="resetItem(v)">重称</button>
                    <button v-if="v.weighMode != '1' && v.weighMode != '25'" @click="saveWeightItem(v, v.weighValue, '结果数据', 'T')">完成</button>
                    <button v-if="v.weighMode == '1' || v.weighMode == '25'" @click="saveWeightItem(v, v.weighData[v.weighData.length - 1].testValue, '结果数据', 'T')">完成</button>
                  </div>
                </div>
              </template>
              <template #label>
                <!-- <div>编号：{{ v.taskItemNo }}</div> -->
                <!-- <div v-if="v.weighMode == '1'">模式：称重模式</div>
                <div v-if="v.weighMode == '10'">模式：皮重、毛重、净重模式</div> -->
                <!-- <div v-if="v.weighMode == '15'">模式：皮重、净重、毛重模式</div> -->
                <!-- <div v-if="v.weighMode == '20'">模式：减重模式(普通)</div>
                <div v-if="v.weighMode == '25'">模式：减重模式(特殊)</div> -->
                <!-- <div v-if="v.weighMode == '40'">模式：干燥失重模式</div> -->
                <!-- <div v-if="v.weighMode == '50'">模式：炽灼残渣模式</div> -->
                <!-- <div v-if="weighData.length > 3"> -->
                <div>模式：{{ v.wordCode }}</div>
                <div>称重项目：{{ v.attributeName }}</div>
                <div>检验项目：{{ v.testAttributeName }}</div>

                <div class="spanStyle">
                  <!-- if((j+1)%3==1){
                  <div>编号：{{ v.taskItemNo }}</div>
                  } -->
                  <div v-if="v.weighMode == '1'">
                    <div class="style1">
                      重
                      <i style="display: inline-block; width: 19.2px"></i>
                      量：
                      <span>{{ v.weighData[v.weighData.length - 1].testValue }}</span>
                    </div>
                  </div>
                  <div v-if="v.weighMode == '25'">
                    <div class="style1">
                      重
                      <i style="display: inline-block; width: 19.2px"></i>
                      量：
                      <span>{{ v.weighData[v.weighData.length - 1].testValue }}</span>
                    </div>
                  </div>
                  <div v-if="v.weighMode == '10'">
                    <div class="style1">
                      皮重：
                      <span>{{ v.weighData[0].testValue }}</span>
                    </div>
                    <div class="style1">
                      毛重：
                      <span>{{ v.weighData[1].testValue }}</span>
                    </div>
                    <div class="style1">
                      净重：
                      <span>{{ v.weighValue }}</span>
                    </div>
                  </div>
                  <!-- <div v-if="v.weighMode == '15'">
                  <div class="style1">
                    皮重：<span>{{ v.weighData[0].testValue }}</span>
                  </div>
                  <div class="style1">
                    净重：<span>{{ v.weighData[1].testValue }}</span>
                  </div>
                  <div class="style1">
                    毛重：<span>{{ v.weighValue }}</span>
                  </div>
                </div> -->
                  <div v-if="v.weighMode == '20'">
                    <div class="style1">
                      使用前：
                      <span>{{ v.weighData[0].testValue }}</span>
                    </div>
                    <div class="style1">
                      使用后：
                      <span>{{ v.weighData[1].testValue }}</span>
                    </div>
                    <div class="style1">
                      结
                      <i style="display: inline-block; width: 19.2px"></i>
                      果：
                      <span>{{ v.weighValue }}</span>
                    </div>
                  </div>
                  <!-- <div v-if="v.weighMode == '40'">
                  <div v-for="(t, j) in v.weighData" :key="j">
                    <div v-if="j == 0" class="style1">
                      恒重前：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j == 1" class="style1">
                      恒重后：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j == 2" class="style1">
                      净<i style="display: inline-block; width: 19.2px"></i
                      >重：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j > 2" class="style1">
                      CN{{ j - 2 }}
                      <i style="display: inline-block; width: 19.2px"></i
                      >：<span>{{ t.testValue }}</span>
                    </div>
                  </div>
                  <div class="style1">
                    结<i style="display: inline-block; width: 19.2px"></i
                    >果：<span>{{ v.weighValue }}%</span>
                  </div>
                </div>
                <div v-if="v.weighMode == '50'">
                  <div v-for="(t, j) in v.weighData" :key="j">
                    <div v-if="j == 0" class="style1">
                      恒重前：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j == 1" class="style1">
                      恒重后：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j == 2" class="style1">
                      净<i style="display: inline-block; width: 19.2px"></i
                      >重：<span>{{ t.testValue }}</span>
                    </div>
                    <div v-else-if="j > 2" class="style1">
                      CN{{ j - 2 }}
                      <i style="display: inline-block; width: 19.2px"></i
                      >：<span>{{ t.testValue }}</span>
                    </div>
                  </div>
                  <div class="style1">
                    结<i style="display: inline-block; width: 19.2px"></i
                    >果：<span>{{ v.weighValue }}%</span>
                  </div>
                </div> -->
                </div>
              </template>
            </van-cell>
            <template #right>
              <van-button square block type="danger" style="height: 100%" text="删除" @click.stop="delItem(v, i)" />
            </template>
          </van-swipe-cell>
        </van-list>
      </div>
    </div>
    <div class="scan" v-if="scanShow">
      <div id="bcid">
        <div style="height: 40%"></div>
        <p class="tip">...载入中...</p>
      </div>
      <footer>
        <button @click="closeModel">退出</button>
      </footer>
    </div>
    <van-popup v-model="showPicker" position="bottom" get-container="body" :lock-scroll="false">
      <van-cascader v-model="cascaderValue" :options="recordArr" @close="showPicker = false" @finish="onFinish" />
    </van-popup>
		<van-popup
      v-model="showMaterialNamePicker"
      position="bottom"
      round
      :style="{ height: '70%' }"
      :lock-scroll="false">
			<van-row
            gutter="20"
            type="flex"
            align="center"
            class="search-box">
            <van-col span="18">
              <van-field
                v-model="keyword"
                name="keyword"
                label="物料名称"
                input-align="center">
              </van-field>
            </van-col>
            <van-col span="6" style="display: flex;align-items: center;">
              <van-button
                type="default"
                size="small"
                style="margin-right: 10px"
                @click="handelMaterialNameReset()">
                重置</van-button
              >
              <van-button type="primary" size="small" @click="handleMaterialNameSearch"
                >查询</van-button
              >
            </van-col>
          </van-row>
					<van-picker
					show-toolbar
					:columns="filterMaterialNamecolumns"
					@confirm="onMaterialNameConfirm"
					@cancel="showMaterialNamePicker = false"
				/>
    </van-popup>
  </div>
</template>

<script>
  import { NavBar, Cell, CellGroup, Notify, Col, Row, DropdownMenu, DropdownItem, Icon, Tag, Button, Popup, Field, Picker, List, SwipeCell, Dialog, Loading, Search, Cascader } from "vant";
  import {
    getTestByTestId,
    getTaskSelect, //回去项目code
    saveTaskItemData, //保存项目
    taskItemWeighAgain,
    saveReckonTaskItemData,
    DeleteTaskAttribute,
    GetTaskItemsTwos,
    GetTaskBatchIDss, //批次接口
    SelectTestProjectAttribute,
    getMaterialSelect,
    GetRecordReportActiveTreeTwo,
		GetMaterialName,
		SelectWeightBatchId
  } from "@/api/base";
  import { GetAttributesByMaterialCode,SelectTestProjectDataTwo } from "@/api/check";
  import { to } from "@/utils";
  import DeviceName from "./components/DeviceName";
  import MaterialType from "./components/MaterialType";
  import MaterialName from "./components/MaterialName";
  import MultSelect from "./components/MultSelect";
  import BatchList from "./components/BatchList";
  // import { ScanBackInfor } from "@/api/resourceReport";
  let scan = null;
  export default {
    name: "weightItem",
    components: {
      [NavBar.name]: NavBar,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
      [Notify.name]: Notify,
      [Col.name]: Col,
      [Row.name]: Row,
      [DropdownMenu.name]: DropdownMenu,
      [DropdownItem.name]: DropdownItem,
      [Icon.name]: Icon,
      [Tag.name]: Tag,
      [Button.name]: Button,
      [Popup.name]: Popup,
      [Field.name]: Field,
      [Picker.name]: Picker,
      [List.name]: List,
      [SwipeCell.name]: SwipeCell,
      [Dialog.name]: Dialog,
      [Loading.name]: Loading,
      [Search.name]: Search,
      [Cascader.name]: Cascader,
      DeviceName,
      MaterialType,
      MaterialName,
      MultSelect,
      BatchList,
    },
    data() {
      return {
				keyword: "",
				showMaterialNamePicker: false,
				materialNamecolumns: [],
				filterMaterialNamecolumns: [],
        finished: false,
        token: "",
        instCode: "", //编号
        deviceName: "",
        // weight: "",
        // unity: "",
        scanShow: false,
        ws: "",
        socket: "",
        socketUrl: "",
        gDomain: "",
        scanType: "",
        scanObj: {},
        timer: null,
        itemList: [],
        weightBatch: "",
        weightBatchArr: [],
        weightNumber: "",
        weightItemObj: {},
        weightValue: "",
        weightValue1: "", //过程称量
        weightValue2: "", //过程称量
        weightValue3: "",
        weightValue4: "",
        weightValue5: "",
        textValue: "", //结果称量
        testNumber: 0, //称量次数
        weightPort: "",
        decimalNum: 4,
        ishandle: false,
        connectState: false,
        searchValue: "", //查询字段
        materialType: "",
        materialTypeName: "",
        materialCode: "",
        materialName: "",
        batch: "",
        deviceArr: [], //多选称重项目编码
        deviceItemCode: "", //称重项目编号
        deviceItemName: "",
        deviceItemArr: [],
        sampleObj: {},
        sampleNum: "",
        batchDataArr: [],
        batchId: "",
        batchIdArr: [],
        materialCodeName: "",
				materialID: "",
        columnsList: [],
        testID: "",
        testStandard: "",
        recordName: "",
        recordCode: "",
        recordArr: [],
        showPicker: false,
        cascaderValue: "",
        weightValueOld: "",
        weighMode: "",
				routeParamsData: {},
      };
    },
    watch: {

      instCode(val) {
        this.socketUrl = "ws://" + this.weightPort + "/" + val;
        if (typeof this.socket.close == "function") {
          this.socket.close();
        }
        if (val) {
          this.connectState = true;
          this.init();
        }
      },
      testNumber(val) {
				debugger
        if (val) {
          if (
            this.weightItemObj.weighMode == "10" ||
            // this.weightItemObj.weighMode == "15" ||
            this.weightItemObj.weighMode == "20"
          ) {
            if (val == 1) {
              this.weightValue1 = this.weightValue;
              this.saveWeightItem(this.weightItemObj, this.weightValue1, "过程数据");
            } else if (val == 2) {
              this.weightValue2 = this.weightValue;
              if (this.weightItemObj.weighMode == "10") {
                this.textValue = parseFloat(Number(this.weightValue2) - Number(this.weightValue1));
              } else if (this.weightItemObj.weighMode == "20") {
                this.textValue = parseFloat(Number(this.weightValue1) - Number(this.weightValue2));
              }
              // else if (this.weightItemObj.weighMode == "15") {
              //   this.textValue = parseFloat(
              //     (Number(this.weightValue1) + Number(this.weightValue2)).toFixed(
              //       5
              //     )
              //   );
              // }
              this.textValue = this.getDecimaZero(this.textValue, this.decimalNum);
              this.saveWeightItem(this.weightItemObj, this.weightValue2, "过程数据");
            }
          } else if (this.weightItemObj.weighMode == "1") {
            this.saveWeightItem(this.weightItemObj, this.weightValue, "过程数据");
          } else if (this.weightItemObj.weighMode == "25") {
            this.saveWeightItem(this.weightItemObj, Math.abs(this.weightValue), "过程数据");
          }
        }
      },
      batch(val) {
        if (val) {
          // this.fetchItems();
          this.SelectTestProject();
        }
      },
    },
    mounted() {
      this.gDomain = localStorage.getItem("domainKey");
      this.token = localStorage.getItem("tokenKey");

			this.routeParamsData = this.$route.params.param||{};
			console.log('this.routeParamsData',this.routeParamsData)

      // this.getMaterialType();
      if (this.gDomain.includes("//")) {
        let dStr = this.gDomain.split("//")[1];
        if (dStr.includes(":")) {
          this.weightPort = dStr.split(":")[0] + ":10002";
          // this.weightPort = dStr.split(":")[0] + ":20001";
        } else {
          this.weightPort = dStr;
        }
      }
      // this.getItemCode();
      //     this.onSearch("one"); //默认查询
			this.getMaterialNameColumn();
      // this.getBatchData(); //批次信息
      // this.fetchColumns();
    },
    beforeUnmount() {
      if (scan && scan != "") {
        scan.close();
      }
    },
    methods: {
			getMaterialNameColumn() {
				let params = {
					pageModel:{
						Search: [''],
						Token: this.token,
					}
				};
				GetMaterialName(params).then((res) => {
					if (res.ErrorCode == 0) {
						res.Result = res.Result.map((item) => {
							return {
								...item,
								text: item.Name,
								value: item.Value,
							};
						});
						this.materialNamecolumns = res.Result||[];
						this.filterMaterialNamecolumns = res.Result||[];
						if(this.routeParamsData.materialCode){
							let obj = this.filterMaterialNamecolumns.find(item=>item.MaterialCodes.includes(this.routeParamsData.materialCode));
							if(obj){
								this.materialName = obj.text;
								this.materialCode = obj.value;
								this.materialID = obj.value;
								this.getBatchIdColumn(); //获取批次信息
							}
						}
					} else {
						this.$toast(res.ErrorMsg);
					}
				});
			},
			getBatchIdColumn() {
				let params = {
					Token: this.token,
					materialID: this.materialID,
				};
				SelectWeightBatchId(params).then(res=>{
					if(res.ErrorCode == 0){
					  console.log(res)
						this.batchIdArr = res.Result.map(e=>({...e,text:e.BatchID,value:e.BatchID}))||[];
						if(this.routeParamsData.batchID){
							let obj = this.batchIdArr.find(item=>item.BatchID == this.routeParamsData.batchID);
							if(obj){
								this.testID = obj.TestID;
								this.testStandard = obj.testStandard;
								this.batch = obj.value;
								this.batchId = obj.value;
								this.onSearch();
							}
						}
					}
				})
			},
			onMaterialNameConfirm(item) {
        console.log('item',item)
				this.materialName = item.text;
				this.materialCode = item.value;
				this.materialID = item.value;
				this.showMaterialNamePicker = false;
				this.getBatchIdColumn(); //获取批次信息
      },
      handleMaterialNameSearch() {
				this.filterMaterialNamecolumns = this.materialNamecolumns.filter(item => {
					return item.text.toLowerCase().includes(this.keyword.toLowerCase());
				})
				console.log("search",this.filterMaterialNamecolumns);
      },
      handelMaterialNameReset() {
				this.keyword = "";
				this.filterMaterialNamecolumns = this.materialNamecolumns;
      },
      changeMater(value) {
        this.materialCode = value.value;
        this.materialCodeName = value.text;
        // this.getBatchData(value.value); //批次信息
      },
      async fetchColumns() {
        let that = this;
        const queryParams = {
          pageModel: { Token: this.token, Search: "" },
        };
        this.loading = true;
        const [err, res] = await to(getMaterialSelect(queryParams));
        this.loading = false;
        console.log(res);
        if (!err) {
          this.columnsList = res.result;
        }
      },
      onClickLeft() {
        if (this.socket && this.socket != "") {
          this.socket.close();
        }
        if (scan && scan != "") {
          scan.close();
        }
        this.$router.back();
      },
      onClickRight() {
        this.onSearch();
      },
      resetDevice() {
        this.socketUrl = "ws://" + this.weightPort + "/" + this.instCode;
        this.init();
      },
      openScan(type, v, i) {
        let that = this;
        this.scanType = type;
        this.scanShow = true;
        if (type == "sample") {
          this.sampleObj = v;
          this.sampleNum = i;
          let classArr = this.$refs.sampleConfirm;
          let classArr1 = this.$refs.startWeight;
          if (classArr && classArr.length > 0) {
            classArr.map((item, index) => {
              item.style.background = "#cdcbcb";
              item.style.color = "#323233";
              classArr1[index].style.background = "#cdcbcb";
              classArr1[index].style.color = "#323233";
              classArr1[index].disabled = true;
            });
          }
        }

        this.timer = setTimeout(that.startRecognize, 500);
      },
      startRecognize() {
        let that = this;
        this.timer = null;
        if (!window.plus) return;
        scan = new plus.barcode.Barcode("bcid");
        scan.onmarked = onmarked;
        scan.start();
        async function onmarked(type, result, file) {
          switch (type) {
            case plus.barcode.QR:
              type = "QR";
              break;
            case plus.barcode.EAN13:
              type = "EAN13";
              break;
            case plus.barcode.EAN8:
              type = "EAN8";
              break;
            default:
              type = "其它" + type;
              break;
          }

          scan.close();
          that.scanShow = false;
          if (that.scanType == "device") {
            var str = decodeURIComponent(result);
            var strObj = JSON.parse(str);
            that.deviceName = strObj.equipmentName;
            that.instCode = strObj.equipmentCode;
          } else if (that.scanType == "material") {
            //或去物料类型
            that.getScanType(JSON.parse(result).testID);
          } else if (that.scanType == "sample") {
            that.getScanType(JSON.parse(result).testID);
          }
        }
      },
      closeModel() {
        this.scanShow = false;
        if (!window.plus) return;
        scan.close();
      },
      getDeviceCode(val) {
        this.deviceName = val.text;
        this.instCode = val.value;
      },
      async getScanType(id) {
        let params = {
          queryModel: {
            Code: id,
            Token: this.token,
          },
        };
        const [err, res] = await to(getTestByTestId(params));
        this.scanObj = res.Result;
        this.materialName = "";
        if (this.scanType == "material") {
          this.materialName = res.Result.materialName;
          this.materialType = res.Result.materialType;
          this.materialCode = res.Result.materialCode;

          this.materialTypeName = res.Result.materialTypeName;
          this.batchId = res.Result.batchID;
          this.testID = res.Result.testID;
          this.batch = res.Result.batchID;
        }

        if (this.scanType == "sample") {
          if (this.scanObj.materialCode == this.sampleObj.materialCode && this.scanObj.batchID == this.sampleObj.batchID && this.scanObj.testID == this.sampleObj.testID) {
            let classArr = this.$refs.sampleConfirm;
            let classArr1 = this.$refs.startWeight;
            classArr[this.sampleNum].style.background = "#49bbef";
            classArr[this.sampleNum].style.color = "#fff";
            classArr1[this.sampleNum].disabled = false;
          }
        }
      },
      async fetchItems() {
        let that = this;
        let queryParams = {
          materialCode: this.materialCode,
          StandardCode: this.testStandard,
          TestID: this.testID,
          Token: this.token,
        };
        const [err, res] = await to(GetRecordReportActiveTreeTwo(queryParams));
        if (err) return;
        let code = res.ErrorCode;
        if (code == 0) {
          let result = res.Result;
          if (!result || result.length == 0) return false;
          that.dowhile(result);
          that.recordArr = result;
        }
      },
      onFinish({ selectedOptions }) {
        this.showPicker = false;
        let len = selectedOptions.length;
        let toDetail = selectedOptions[len - 1];
        this.recordName = toDetail.text;
        this.recordCode = toDetail.value;
      },
      dowhile(b) {
        for (let i = 0; i < b.length; i++) {
          b[i].text = b[i].name;
          b[i].value = b[i].code;
          if (b[i].children && b[i].children.length > 0) {
            this.dowhile(b[i].children);
          } else {
            delete b[i].children;
          }
        }
      },
      init: function () {
        if (typeof WebSocket === "undefined") {
          // alert("您的浏览器不支持socket");
        } else {
          // 实例化socket
          this.socket = new WebSocket(this.socketUrl);
          // 监听socket连接
          this.socket.onopen = this.open;
          // 监听socket错误信息
          this.socket.onerror = this.error;
          //关闭链接
          this.socket.onclose = this.close;
          // 监听socket消息
          this.socket.onmessage = this.getMessage;
        }
      },
      open: function () {
        console.log("socket连接成功");
        Notify({ type: "success", message: "天平连接成功" });
				// alert('天平连接成功');
        this.connectState = false;
      },
      error: function () {
        console.log("连接错误");
        Notify({ type: "danger", message: "天平连接失败" });
        this.connectState = false;
      },
      getMessage: function (msg) {
				// debugger
				// alert('获取到消息：'+ msg);
        let weightMsg = JSON.parse(msg.data).message;
				// alert('weightMsg：'+ weightMsg);
        if (weightMsg) {
					// alert('weightMsg存在');
          if (weightMsg.includes("连接成功")) {
            // this.ishandle = false;
            Notify({ type: "success", message: weightMsg });
          } else {
            // this.ishandle = true;
            Notify({ type: "danger", message: weightMsg });
          }
        } else {
					console.log(this.weighMode)
          if (this.weighMode == "10" || this.weighMode == "20") {
            this.weightValue = JSON.parse(msg.data).weight;
            if (this.weightValue && this.weightValue != this.weightValueOld) {
              this.testNumber++;
              console.log(this.testNumber);
              console.log(this.weightValue);
              var weightStr = this.weightValue.toString();
              if (weightStr.indexOf(".")) {
                this.decimalNum = weightStr.split(".")[1].length;
              }
              this.weightValueOld = this.weightValue;
            }
          } else {
            this.weightValue = JSON.parse(msg.data).weight;
						console.log('this.weightValue',this.weightValue)
            this.testNumber++;
						console.log('this.testNumber',this.testNumber)
            var weightStr = this.weightValue.toString();
            if (weightStr.indexOf(".")) {
              this.decimalNum = weightStr.split(".")[1].length;
            }
          }
        }
        this.connectState = false;

        // console.log(this.testNumber, this.weightValue);
        // this.unity = JSON.parse(msg.data).unity;
      },
      close() {
        console.log("关闭链接");
        this.connectState = false;
      },
      //获取项目列表
      getItemCode: function () {
        let params = {
          Token: this.token,
          search: [""],
        };
        getTaskSelect(params)
          .then((response) => {
            if (response.ErrorCode == 0) {
              this.weightBatchArr = response.Result;
            } else {
              Notify({ type: "danger", message: response.message });
            }
          })
          .catch(() => {});
      },
      getWeightNum (v, i) {
				console.log(this.testID)
        this.testNumber = 0;
        let that = this;
        this.weightItemObj = v;
        this.weighMode = v.weighMode;
        let classArr = this.$refs.startWeight;
        classArr.map((item) => {
          item.style.background = "#cdcbcb";
          item.style.color = "#323233";
        });
        classArr[i].style.background = "#49bbef";
        classArr[i].style.color = "#fff";
      },
      resetItem: function (v) {
        this.testNumber = 0;
        let that = this;
        let params = {
          Token: this.token,
          TestID: v.testID,
          RecordCode: v.recordCode,
          AttributeCode: v.attributeCode,
          DeviceCode: this.instCode,
        };
        taskItemWeighAgain(params)
          .then((response) => {
            if (response.ErrorCode == 0) {
              that.onSearch();
            } else {
              Notify({ type: "danger", message: response.ErrorMsg });
            }
          })
          .catch((response) => {
						Notify({ type: "danger", message: response.ErrorMsg });
					});
      },
      SaveReckonTaskItemData: function (v, val, isT) {
        let that = this;
        if (val == 0 || val) {
          val = val.toString();
          let params = {
            Token: this.token,
            TestID: this.testID,
            RecordCode: v.recordCode,
            AttributeCode: v.attributeCode,
            DeviceCode: this.instCode,
            testValue: val,
          };
          saveReckonTaskItemData(params)
            .then((response) => {
              if (response.ErrorCode == 0) {
                that.onSearch();
                if (isT == "T") {
                  Notify({ type: "success", message: "提交成功！" });
                }
              } else {
                Notify({ type: "danger", message: response.message });
              }
            })
            .catch(() => {});
        } else {
          Notify({ type: "warning", message: "数据不能为空！" });
        }
      },
      saveWeightItem: function (v, val, type, isT) {
        // console.log(v, val, type, isT);
        let that = this;
        let typeCode = "";
        if (val && val != "") {
          val = this.getDecimaZero(val, this.decimalNum);
          if (type == "过程数据") {
            typeCode = 1;
          } else {
            typeCode = 2;
            // var classArr = this.$refs.sampleConfirm;
            let classArr1 = this.$refs.startWeight;
            if (classArr1 && classArr1.length > 0) {
              classArr1.map((item, index) => {
                item.style.background = "#cdcbcb";
                item.style.color = "#323233";
                // classArr1[index].style.background = "#cdcbcb";
                // classArr1[index].style.color = "#323233";
              });
            }
          }
          let params = {
            Token: this.token,
            TestID: this.testID,
            RecordCode: v.recordCode,
            AttributeCode: v.attributeCode,
            RecordType: typeCode,
            DeviceCode: this.instCode,
            testValue: val,
          };
          saveTaskItemData(params)
            .then((response) => {
              if (response.ErrorCode == 0) {
                if (
                  v.weighMode == "10" ||
                  v.weighMode == "20"
                  // ||v.weighMode == "15"
                ) {
                  if (that.testNumber == 2) {
                    if (val && val != "") {
                      this.SaveReckonTaskItemData(this.weightItemObj, this.textValue, isT);
                    }
                  } else {
                    that.onSearch();
                  }
                } else if (v.weighMode == "1" || v.weighMode == "25") {
                  if (typeCode == 1) {
                    that.onSearch();
                  } else {
                    if (val && val != "") {
                      this.SaveReckonTaskItemData(v, val, isT);
                    }
                  }
                }
              } else {
                Notify({ type: "danger", message: response.message });
              }
            })
            .catch(() => {});
        } else {
          Notify({ type: "warning", message: "数据不能为空！" });
        }
      },
      delItem(v, i) {
        let that = this;
        Dialog({
          message: "确定删除吗？",
        })
          .then(() => {
            let params = {
              Token: this.token,
              AttributeCode: v.attributeCode,
              TaskID: v.taskID,
            };
            DeleteTaskAttribute(params)
              .then((response) => {
                if (response.ErrorCode == 0) {
                  that.onSearch();
                }
              })
              .catch(() => {});
          })
          .catch(() => {});
      },
      getDecimaZero(number, bitNum) {
        let f_x = parseFloat(number).toFixed(this.decimalNum);
        if (isNaN(f_x)) {
          return 0;
        }
        let s_x = f_x.toString();
        let pos_decimal = s_x.indexOf(".");
        if (pos_decimal < 0) {
          pos_decimal = s_x.length;
          s_x += ".";
        }
        while (s_x.length <= pos_decimal + bitNum) {
          s_x += "0";
        }
        return s_x;
      },
      SelectTestProject() {
        let params = {
          Token: this.token,
          search: [this.batch, this.materialCode, ""],
        };
        SelectTestProjectAttribute(params).then((res) => {
          res.Result.map((item) => {
            item.value = item.attributeCode;
            item.text = item.attributeName;
          });
          this.deviceItemArr = res.Result;
        });
      },
      //查询事件
      onSearch(val) {
        let _this = this;
        if (val == "handleSearch") {
          // var classArr = this.$refs.sampleConfirm;
          let classArr1 = this.$refs.startWeight;
          if (classArr1 && classArr1.length > 0) {
            classArr1.map((item, index) => {
              item.style.background = "#cdcbcb";
              item.style.color = "#323233";
              // classArr1[index].style.background = "#cdcbcb";
              // classArr1[index].style.color = "#323233";
              // classArr1[index].disabled = true;
            });
          }
        }
        let itemStr = "";
        if (this.deviceArr.length > 0) {
          itemStr = this.deviceArr.toString();
        }

        let params = {
          Token: this.token,
          materialID: this.materialCode,
					batchID: this.batch,
        };
				this.$toast.loading({
					duration: 0
				})
        SelectTestProjectDataTwo(params)
          .then((response) => {
            if (response.ErrorCode == 0) {
              let itemArr = [];
              response.Result.map((item) => {
                if (
                  item.weighMode == "10" ||
                  item.weighMode == "20"
                  // ||item.weighMode == "15"
                ) {
                  // item.weighData = [];
                  if (item.weighData.length == 0) {
                    item.weighData.push({ testValue: "" });
                    item.weighData.push({ testValue: "" });
                  } else if (item.weighData.length == 1) {
                    item.weighData.push({ testValue: "" });
                  }
                } else if (item.weighMode == "1" || item.weighMode == "25") {
                  if (item.weighData.length == 0) {
                    item.weighData.push({ testValue: "" });
                  }
                }
              });

              //   _this.deviceItemArr = _this.todo(itemArr, "value");
              this.itemList = response.Result;
            } else {
              Notify({ type: "danger", message: response.message });
            }
          })
          .catch(() => {}).finally(() => {
          	this.$toast.clear()
          })
      },
      getItemData() {
        let _this = this;
        let q = {
          queryModel: {
            Token: this.token,
            Code: this.materialCode,
          },
        };
        GetAttributesByMaterialCode(q)
          .then((response) => {
            if (response.ErrorCode == 0) {
              let res = response.Result;
              if (res && res.length > 0) {
                res.map((item) => {
                  item.value = item.attributeCode;
                  item.text = item.attributeName;
                });
                _this.deviceItemArr = res;
              }
            }
          })
          .catch(() => {});
      },
      updataDeviceItemCode(code) {
        console.log(code, "code");
        this.deviceArr = [];
        if (code && code.length > 0) {
          code.map((item) => {
            this.deviceArr.push(item.attributeCode);
          });
        }
        this.onSearch();
      },
			
      getBatchData: function () {
        let _this = this;
        let params = {
          Token: this.token,
          search: ["", this.materialCode],
        };
        _this.batchIdArr = [];
        GetTaskBatchIDss(params)
          .then((response) => {
            if (response.ErrorCode == 0) {
              let res = response.Result;
              if (res && res.length > 0) {
                res.map((item) => {
                  item.value = item.batchID;
                  item.text = item.batchID;
                });
                _this.batchIdArr = res;
              }
            }
          })
          .catch(() => {});
      },
      updataBatch: function (val) {
        this.testID = val.TestID;
        this.testStandard = val.testStandard;
        this.batch = val.value;
				this.batchId = val.value;
        this.onSearch();
      },
      todo: function (arr, key) {
        let set = [];
        let result = [];
        for (let val of arr) {
          if (!set.includes(val[key])) {
            result.push(val);
            set.push(val[key]);
          }
        }
        return result;
      },
    },
    unmounted() {
      // 销毁监听
      if (typeof this.socket.close == "function") {
        this.socket.close();
      }
    },
  };
</script>
<style>
  .van-nav-bar__title {
    color: #fff;
  }
  /* .van-icon-arrow-left {
  color: #fff !important;
} */
  .van-cell__title {
    text-align: left;
    font-weight: 500;
  }
  .van-dropdown-menu__bar {
    box-shadow: 0 0 0;
    height: 36px;
  }
  .item-style .van-row .van-col .van-field__control {
    text-align: center;
  }
</style>
<style scoped lang="less">
.search-box{
	position: absolute;
    top: 0;
    z-index: 9;
    width: 40%;
    left: 50%;
    transform: translateX(-50%);
}
  .weightItem {
    height: 100%;
    overflow-y: hidden;
    margin: 0;
    padding: 0;
  }
  .nav-bar {
    background-color: #49bbef;
  }
  .item-style {
    font-size: 0.34rem;
    height: calc(100% - 40px);
    overflow-y: auto;
  }
  .scan {
    height: 100%;
    width: 100%;
    position: fixed;
    left: 0;
    right: 0;
    top: 0;

    #bcid {
      width: 100%;
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 1rem;
      text-align: center;
      color: #fff;
      background: #ccc;
      font-size: 20px;
      z-index: 999;

      .closeModel {
        position: absolute;
        top: 20px;
        right: 20px;
      }
    }

    footer {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      bottom: 0;
      height: 1rem;
      font-size: 20px;

      button {
        height: 100%;
        width: 100%;
        border: none;
        background: #f3f3f3;
      }
    }
  }
  /deep/.van-dropdown-menu__title {
    width: 4.6rem;
    height: 0.69rem;
    border: 1px solid #ddd;
    font-size: 0.34rem;
    text-align: center;
    margin-right: 0.21rem;
  }
  /deep/.van-dropdown-menu__title::after {
    display: none;
  }
  .deviceStyle /deep/.van-cell__title {
    width: 4.6em;
  }
  .titleStyle {
    display: flex;
    justify-content: space-between;
  }
  .controlBtn {
    display: flex;
    align-items: center;
  }
  .controlBtn button {
    margin-right: 8px;
    height: 22px;
    line-height: 18px;
    font-size: 12px;
    padding: 0 10px;
    border-radius: 3px;
  }
  .controlBtn button:last-child {
    margin-right: 0;
  }
  .spanStyle span {
    border: 1px solid #ccc;
    display: inline-block;
    text-align: center;
    width: 200px;
    height: 20px;
  }
  .spanStyle .van-cell {
    padding-top: 2px;
    padding-bottom: 2px;
  }
  .style1 {
    display: flex;
    margin-bottom: 5px;
  }

  /deep/.van-popup {
    overflow-y: hidden !important;
  }

  .checkItem button {
    border: none;
    background: #cdcbcb;
  }
  /deep/.van-dropdown-item {
    top: 3rem !important;
  }
  /deep/.van-button--danger {
    color: #fff;
    background-color: #ee0a24 !important;
    border: 0.02667rem solid #ee0a24 !important;
  }
  /deep/.van-search__content {
    padding-left: 0;
  }

  /deep/.van-search .van-cell {
    background-color: #fff;
  }
  /deep/.van-swipe-cell__wrapper {
    border-bottom: 1px dashed #969799;
  }
  .readonly /deep/.van-field__body {
    background: #ddd;
  }
  /deep/.van-cell {
    padding: 0.2rem 0.4rem;
  }
  /deep/.van-field__body {
    border-radius: 2px !important;
    border: 1px solid #ddd;
  }
  /deep/.van-cell {
    font-size: 0.32rem;
  }
  :deep(.van-cascader__options) {
    --van-cascader-options-height: 60vh;
  }

  /deep/.van-cascader__header {
    height: 1rem !important;
  }

  /deep/.van-cascader__tabs {
    height: calc(100% - 1rem);
  }

  /deep/.van-tabs__wrap {
    height: 1rem !important;
  }

  /deep/.van-tabs__nav--complete {
    height: 1rem !important;
  }
</style>
